import LinkedList from './01_实现单向链表LinkedList'

class CircularLinkedList<T> extends LinkedList<T>{
    // 重新实现的方法 append
    // 追加节点,只在最后的位置插入
    append(value:T):void{
        super.append(value)
        // 拿到最后一个节点，将其指向第一个节点
        this.tail!.next = this.head;
    }

    insert(value: T, position: number): boolean {
        const isSuccess = super.insert(value,position)

        // 因为里面已经进行length--了
        if(isSuccess && (position === this.length -1 || position === 0)){
            // 因为调用了上面的super方法,此时的this.tail已经是最后一个插入的新节点了
            // 如果插入的是0的位置，则this.head也是插入后最新的节点
            this.tail!.next = this.head
        }
        return isSuccess
    }

    removeAt(position: number): T | null {
        const value = super.removeAt(position)
        // 上面已经进行了length--
        // 如果我们把最后一个节点删除的话，此时的tail不一定有值
        if(value && this.tail && (position === this.length || position === 0)){
            this.tail!.next = this.head
        }
        return value
    }
}

const circularLink =new CircularLinkedList<string>()

circularLink.append('aaa')
circularLink.append('bbb')
circularLink.append('ccc')
circularLink.append('ddd')
circularLink.insert('555',2)
circularLink.insert('666',0)
circularLink.insert('777',6)


console.log(circularLink.get(0))
console.log(circularLink.get(1))
console.log(circularLink.get(2))

circularLink.update('why',1)
circularLink.update('iiiii',2)

circularLink.remove('aaa')

circularLink.remove('666')

console.log(circularLink.indexOf('iiiii'))

console.log(circularLink.indexOf('iii'))

console.log(circularLink.isEmpty())
console.log(circularLink.size())

// console.log('--------------测试---------')
// circularLink.traverse()
// circularLink.removeAt(6)

circularLink.traverse()

